package edu.gtcfla.km.appmodules.web;

import java.util.LinkedHashSet;
import java.util.List;
import java.util.Map;
import java.util.Set;

import javax.servlet.http.HttpServletRequest;

import org.apache.shiro.authz.annotation.RequiresUser;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Lazy;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.vsg.biz.BusinessOperationException;
import org.vsg.common.i18n.I18nMessageService;
import org.vsg.common.web.json.ListResult;
import org.vsg.common.web.json.SubmitResult;
import org.vsg.security.annotation.RegisterRequestPermissionStrategy;

import edu.gtcfla.km.appmodules.service.CategoryService;
import edu.gtcfla.km.appmodules.service.UserGroupPermissionService;
import edu.gtcfla.km.appmodules.service.UserPermissionService;
import edu.gtcfla.km.appmodules.vo.CategoryFormVO;
import edu.gtcfla.km.appmodules.vo.CategoryNodeVO;
import edu.gtcfla.km.appmodules.vo.UserDirectPermissionListVO;
import edu.gtcfla.km.appmodules.vo.UserGroupPermissionListVO;


@Controller
@Lazy
@RequestMapping(edu.gtcfla.km.core.ApplicationConstant.DATA_RERESOURCE)
public class CategoryController {
	
	@Autowired(required=false)
	private CategoryService categoryService;
	
	@Autowired(required=false)
	private UserPermissionService userPermissionService;
	
	@Autowired(required=false)
	private UserGroupPermissionService userGroupPermissionService;
	
	@Autowired(required =false)
	private I18nMessageService i18nMessageService;	
	
	private final String modulePath = "/knowledge";	
	
	@RequiresUser
	@RegisterRequestPermissionStrategy(
		value = modulePath+"/category/tree.json",
		skipCheck = true
	)		
	@RequestMapping(value = modulePath+"/category/tree.json")
	public @ResponseBody Set<CategoryNodeVO> accessTreeCategries(HttpServletRequest request) throws Exception {
		Set<CategoryNodeVO> allData =  categoryService.getTreeForAllCategories();

		return allData;

	}	

	@RequiresUser
	@RegisterRequestPermissionStrategy(
		value = modulePath+"/category/submit_addcate.json",
		skipCheck = true
	)		
	@RequestMapping(value = modulePath+"/category/submit_addcate.json")
	public @ResponseBody SubmitResult accessAdd(CategoryFormVO formView) throws Exception {
		
		// --- map to json object data ---
		SubmitResult result = new SubmitResult();
		
		try {
			
			categoryService.addCategory(formView);
			result.setSuccess(true);
			//String msg = i18nMessageService.getMessage("module-client.company.add.success", null);
			result.setMsg("添加分类成功");
			
		} catch (BusinessOperationException e) {

			e.printStackTrace();
			result.setSuccess(false);
			String msg = i18nMessageService.getMessage("module-client.company.add.error", null);
			result.setMsg(msg);

		
		}

		return result;
	}	
	
	
	@RequiresUser
	@RegisterRequestPermissionStrategy(
		value = modulePath + "/category/submit_deletecategories.json",
		skipCheck = true
	)		
	@RequestMapping(value = modulePath + "/category/submit_deletecategories.json")
	public @ResponseBody SubmitResult accessDeleteCompanies(@RequestBody List<String> receiveValues) throws Exception {
		
		
		// --- map to json object data ---
		SubmitResult result = new SubmitResult();
		
		try {
			if ( receiveValues != null && !receiveValues.isEmpty() ) {
				categoryService.deleteCategoryIds( receiveValues.toArray(new String[0]) );
			}			
			result.setSuccess(true);
			//String msg = i18nMessageService.getMessage("module-client.company.delete.success", null);
			result.setMsg("分类删除成功");
			
		} catch (BusinessOperationException e) {

			e.printStackTrace();
			result.setSuccess(false);
			String msg = i18nMessageService.getMessage("module-client.company.delete.error", null);
			result.setMsg(msg);

		
		}

		return result;
	}
	
	

	@RequiresUser
	@RegisterRequestPermissionStrategy(value = modulePath+"/category/update_all.json", skipCheck = true)
	@RequestMapping(value = modulePath+"/category/update_all.json")
	public @ResponseBody SubmitResult accessUpdateMenus(@RequestBody List<Map<String,Object>> receiveValues)
			throws Exception {


		Set<CategoryFormVO> cateFormList = new LinkedHashSet<CategoryFormVO>();
		
		for (Map<String,Object> item : receiveValues) {
			
			CategoryFormVO cateForm = new  CategoryFormVO(); 
			cateForm.setId( (String)item.get("id"));
			cateForm.setName( (String) item.get("text"));
			cateForm.setParentId( (String)item.get("parentId") );

			cateFormList.add(cateForm);
		}
		
		// --- remove user id ---

		SubmitResult result = new SubmitResult();
		try {

			categoryService.updateAll(cateFormList);

			result.setSuccess(true);
			
			//String msg = i18nMessageService.getMessage("module-admin.menu.update.success", null);
			result.setMsg("更新成功");

		} catch (Exception se) {
			// TODO Auto-generated catch block
			se.printStackTrace();
			result.setSuccess(false);
			String msg = i18nMessageService.getMessage(
					"module-admin.menu.update.error", null);
			result.setMsg(msg);
		}



		return result;
	}
	
	
	@RequiresUser
	@RegisterRequestPermissionStrategy(value = modulePath+"/category/list_direct_userperms.json", skipCheck = true)
	@RequestMapping(value = modulePath+"/category/list_direct_userperms.json")
	public @ResponseBody ListResult accessListDirectUserPerms(String categoryId , String query)
			throws Exception {
		
		if (categoryId != null && categoryId.equals("root")) {
			categoryId = "";
		}

		Set<UserDirectPermissionListVO>  userDirPermList =   userPermissionService.listUserPermission(categoryId, query);
		
		ListResult lr = new ListResult();
		lr.setRows(userDirPermList);
		lr.setResults(userDirPermList.size());

		return lr;
	}

	@RequiresUser
	@RegisterRequestPermissionStrategy(value = modulePath+"/category/list_usergroupperms.json", skipCheck = true)
	@RequestMapping(value = modulePath+"/category/list_usergroupperms.json")
	public @ResponseBody ListResult accessListUserGroupPerms(String categoryId , String query)
			throws Exception {
		
		if (categoryId != null && categoryId.equals("root")) {
			categoryId = "";
		}

		Set<UserGroupPermissionListVO>  userGroupPermList =   userGroupPermissionService.listUserGroupPermission(categoryId, query);
		
		ListResult lr = new ListResult();
		lr.setRows(userGroupPermList);
		lr.setResults(userGroupPermList.size());

		return lr;
	}	
	
	
	@RequiresUser
	@RegisterRequestPermissionStrategy(value = modulePath+"/category/update_direct_userperms.json", skipCheck = true)
	@RequestMapping(value = modulePath+"/category/update_direct_userperms.json")
	public @ResponseBody SubmitResult accessUpdateDirectUserPerms(String categoryId , @RequestBody List<Map<String,Object>> receiveValues)
			throws Exception {

		Set<UserDirectPermissionListVO> resPerms = new LinkedHashSet<UserDirectPermissionListVO>();
		
		for (Map<String,Object> item : receiveValues) {

			UserDirectPermissionListVO listVo = new UserDirectPermissionListVO();
			listVo.setId( (String)item.get("id") );
			listVo.setUserId( (String)item.get("userId") );
			listVo.setUserName( (String)item.get("userName") );
			Boolean cateViewBool = (Boolean)item.get("cateView");
			if (cateViewBool) {
				listVo.setCateView((short)1);
			}
			Boolean cateAddingBool = (Boolean)item.get("cateAdding");
			if (cateAddingBool) {
				listVo.setCateAdding((short)1);
			}
			Boolean cateEditingBool = (Boolean)item.get("cateEditing");
			if ( cateEditingBool ) {
				listVo.setCateEditing( (short)1 );
			}
			Boolean cateDeletingBool = (Boolean)item.get("cateDeleting");
			if ( cateDeletingBool ) {
				listVo.setCateDeleting( (short)1 );
			}
			Boolean kmAddingBool = (Boolean)item.get("kmAdding");
			if ( kmAddingBool ) {
				listVo.setKmAdding( (short)1 );
			}
			Boolean kmEditingBool = (Boolean)item.get("kmEditing");
			if ( kmEditingBool ) {
				listVo.setKmEditing( (short)1 );
			}
			Boolean kmDeletingBool = (Boolean)item.get("kmDeleting");
			if ( kmDeletingBool ) {
				listVo.setKmDeleting( (short)1 );
			}
			Boolean kmViewBool = (Boolean)item.get("kmView");
			if ( kmViewBool ) {
				listVo.setKmView( (short)1 );
			}
			Boolean isAdminBool = (Boolean)item.get("isAdmin");
			if ( isAdminBool ) {
				listVo.setIsAdmin( (short)1 );
			}
			
			resPerms.add( listVo );


		}
		
		// --- remove user id ---


		SubmitResult result = new SubmitResult();
		try {
			
			userPermissionService.updateUserPermissions(categoryId, resPerms);


			result.setSuccess(true);
			String msg = "更新成功";
			/*
			String msg = i18nMessageService.getMessage(
					"module-admin.menu.update.success", null);
					*/
			result.setMsg(msg);

		} catch (Exception se) {
			// TODO Auto-generated catch block
			se.printStackTrace();
			result.setSuccess(false);
			String msg = i18nMessageService.getMessage(
					"module-admin.menu.update.error", null);
			result.setMsg(msg);
		}



		return result;
	}
	
	
	
	@RequiresUser
	@RegisterRequestPermissionStrategy(value = modulePath+"/category/update_usergroupperms.json", skipCheck = true)
	@RequestMapping(value = modulePath+"/category/update_usergroupperms.json")
	public @ResponseBody SubmitResult accessUpdateUserGroupPerms(String categoryId , @RequestBody List<Map<String,Object>> receiveValues)
			throws Exception {

		Set<UserGroupPermissionListVO> resPerms = new LinkedHashSet<UserGroupPermissionListVO>();
		
		for (Map<String,Object> item : receiveValues) {

			UserGroupPermissionListVO listVo = new UserGroupPermissionListVO();
			listVo.setId( (String)item.get("id") );
			listVo.setUserGroupId( (String)item.get("userGroupId") );
			listVo.setGroupName( (String)item.get("groupName") );
			
			Boolean onlyGroupCateViewBool = (Boolean)item.get("onlyGroupCateView");
			if (onlyGroupCateViewBool) {
				listVo.setOnlyGroupCateView( (short)1 );
			}			
			Boolean cateAddingBool = (Boolean)item.get("cateAdding");
			if (cateAddingBool) {
				listVo.setCateAdding((short)1);
			}
			Boolean cateEditingBool = (Boolean)item.get("cateEditing");
			if ( cateEditingBool ) {
				listVo.setCateEditing( (short)1 );
			}
			Boolean cateDeletingBool = (Boolean)item.get("cateDeleting");
			if ( cateDeletingBool ) {
				listVo.setCateDeleting( (short)1 );
			}
			Boolean kmAddingBool = (Boolean)item.get("kmAdding");
			if ( kmAddingBool ) {
				listVo.setKmAdding( (short)1 );
			}
			Boolean kmEditingBool = (Boolean)item.get("kmEditing");
			if ( kmEditingBool ) {
				listVo.setKmEditing( (short)1 );
			}
			Boolean kmDeletingBool = (Boolean)item.get("kmDeleting");
			if ( kmDeletingBool ) {
				listVo.setKmDeleting( (short)1 );
			}
			Boolean kmPostBool = (Boolean)item.get("kmView");
			if ( kmPostBool ) {
				listVo.setKmView( (short)1 );
			}
			Boolean isAdminBool = (Boolean)item.get("isAdmin");
			if ( isAdminBool ) {
				listVo.setIsAdmin( (short)1 );
			}
			
			resPerms.add( listVo );


		}
		
		// --- remove user id ---


		SubmitResult result = new SubmitResult();
		try {
			
			userGroupPermissionService.updateUserGroupPermissions(categoryId, resPerms);


			result.setSuccess(true);
			String msg = "更新成功";
			/*
			String msg = i18nMessageService.getMessage(
					"module-admin.menu.update.success", null);
					*/
			result.setMsg(msg);

		} catch (Exception se) {
			// TODO Auto-generated catch block
			se.printStackTrace();
			result.setSuccess(false);
			String msg = i18nMessageService.getMessage(
					"module-admin.menu.update.error", null);
			result.setMsg(msg);
		}



		return result;
	}	
}
